<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/**
 * Handles webservice authentification throught WSSE.
 */
class AuthSigComponent extends ActiveRecord
{
	protected $Auth;
	
	function startup(Controller $Controller)
	{
		if (isset($_SERVER['HTTP_X_API_KEY']))
		{
			$api_key = $_SERVER['HTTP_X_API_KEY'];
			$call_id = $_SERVER['HTTP_X_CALL_ID'];
			
			# timeout
			if (microtime(true) - $call_id >= 120)
			{
				HTTP::status(408);
				die();
			}
			
			# gets secret for api key
			Load::model('ApiKey');
			$api = new ApiKey($api_key);
			
			# checks request sig
			$sig_request = base64_encode(sha1($api_key.$call_id.HTTP::$method.$this->here.$api->secret));
			if ($sig_request !== $_SERVER['HTTP_X_SIG_REQUEST'])
			{
				HTTP::status(403);
				die();
			}
			
			# checks params sig
			if (isset($_POST['f_sig_params']))
			{
				$sig_params = $_POST['f_sig_params'];
				unset($_POST['f_sig_params']);
				
				$str = '';
				foreach($_POST as $k => $v)
				{
					$str .= "$k=$v";
				}
				$_sig_params = base64_encode(sha1($str.$api->secret));
				
				if ($_sig_params !== $sig_params)
				{
					HTTP::status(403);
					die();
				}
			}
			
			# OK
			$Controller->Auth->add_group(empty($api->groups) ? 'webservice' : $api->groups);
		}
	}
}
?>